const GA_ID = "G-217Z2WNE3K";
const ADSENSE_ID = "ca-pub-6468790746781495";
const GAM_BASE_PATH = "/23290075881/";

// 加载GA埋点
const initGtag = () => {
	const script = {
		children: `
  window.dataLayer = window.dataLayer || [];
	function gtag() {dataLayer.push(arguments);}
	gtag("js", new Date());
	gtag("config", "${GA_ID}");`,
		type: "text/javascript",
	};
	const url = {
		src: `https://www.googletagmanager.com/gtag/js?id=${GA_ID}`,
		async: true,
	};
	return [url, script];
};

// 加载posthog
const initPosthog = () => {
	const script = {
		children: `(function initPosthog() {
			!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagPayload isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
			posthog.init('phc_ouOrsXQjlkLgITRTbls4KpLk2c3JZVcanpprD2dSFtg',{api_host:'https://events.apkdownloadzone.com', person_profiles: 'always', advanced_disable_decide: true})
			})();`,
		type: "text/javascript",
	};
	return [script];
};

// 加载pixel
const initPixel = (network: string, pid: string) => {
	let scriptArr: any[] = [];
	switch (network) {
		case "tiktok":
			scriptArr = [...TikTokPixel(pid)];
			break;
		case "bigo":
			scriptArr = [...BigoPixel(pid)];
			break;
		default:
			break;
	}
	return scriptArr;
};

// TikTok Pixel
const TikTokPixel = (pid: string) => {
	const script = {
		children: `!function (w, d, t) {w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie","holdConsent","revokeConsent","grantConsent"],ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e},ttq.load=function(e,n){var r="https://analytics.tiktok.com/i18n/pixel/events.js",o=n&&n.partner;ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._u=r,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};n=document.createElement("script")
            ;n.type="text/javascript",n.async=!0,n.src=r+"?sdkid="+e+"&lib="+t;e=document.getElementsByTagName("script")[0];e.parentNode.insertBefore(n,e)};
            ttq.load('${pid}');
            ttq.page();
            }(window, document, 'ttq');`,
		type: "text/javascript",
	};
	return [script];
};

// bigo
const BigoPixel = (pid: string) => {
	const script = {
		children: `window.bgdataLayer = window.bgdataLayer || [];
                function bge(){bgdataLayer.push(arguments);}
                bge('init', "${pid}");`,
		type: "text/javascript",
	};
	const url = {
		src: `https://api.affiliations.site/ad/events.js?pixel_id=${pid}`,
		async: true,
	};
	return [url, script];
};

// 加载Adsense广告
const initAdsense = (channel: string) => {
	const url = {
		src: `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${ADSENSE_ID}`,
		async: true,
		crossorigin: "anonymous",
		"data-ad-channel": channel
	};
    return [url];
};


// 加载GAM广告
const initGAM = () => {
	const url = {
		src: `https://securepubads.g.doubleclick.net/tag/js/gpt.js`,
		async: true,
		crossorigin: "anonymous",
	};
	return [url];
};

// 初始化GAM广告位（自动广告）
const initGAMSlots = (channel: string) => {
    window.googletag = window.googletag || { cmd: [] };
	let adSlot1, adSlot2, googletag = window.googletag;
    googletag.cmd.push(function() {
		// 插页广告
		adSlot1 = googletag.defineOutOfPageSlot("/23290075881/APKBox_Interstitial", googletag.enums.OutOfPageFormat.INTERSTITIAL)?.addService(googletag.pubads());
		// 顶部锚点广告
		adSlot2 = googletag.defineOutOfPageSlot("/23290075881/APKBox_Top_Anchor",googletag.enums.OutOfPageFormat.TOP_ANCHOR)?.addService(googletag.pubads());
		// 底部锚点广告
		// adSlot3 = googletag.defineOutOfPageSlot("/23290075881/APKBox_Bottom_Anchor", googletag.enums.OutOfPageFormat.BOTTOM_ANCHOR)?.addService(googletag.pubads());
        // 获取所有GAM广告容器
        const adContainers = document.querySelectorAll('[data-gam-id][data-gam-name]');
        
        // 遍历所有广告容器并定义广告位
        adContainers.forEach(container => {
            const adId = container.getAttribute('data-gam-id') || '';
            const adName = container.getAttribute('data-gam-name') || '';
            let adSize = ['fluid'];
            // 定义广告位
            googletag.defineSlot(GAM_BASE_PATH + adName, adSize, adId)
                .addService(googletag.pubads());
            
		});
			// 设置全局配置
		googletag.pubads().setTargeting('afc_channel', channel);
        googletag.pubads().enableSingleRequest();
        googletag.enableServices();

		adSlot1 && googletag.display(adSlot1)
    });
};

//当前页面是否因为点击iframe失去焦点
const isBlurTriggered = ref(false);

// 跟踪广告点击
const trackAdClick = () => {
	let ACTIVELEMENT = document.activeElement;
	if (!ACTIVELEMENT) return;

	let page = window.location.pathname.split('/')[1].replace(/^\w/, (c) => c.toUpperCase());
	if (page === 'Top-rank') {
		page = 'List'
	}
	if (page === 'Details') {
		page = 'Detail'
	}

	const adAuto = ACTIVELEMENT.closest("[data-vignette-loaded], [data-ad-format], [data-ad-slot], [data-anchor-shown]");
	let isGAM = false, isAFC = false, isInterstitial = false, isInPageAd = false, isDisplayAd = false, isAnchorAd = false, isAutoAnchorAd = false;
	if (adAuto) {
		// 判断是否为GAM和AFC
		isGAM = adAuto.id.includes('gpt')
		isAFC = adAuto.classList.contains('adsbygoogle-noablate');

		isInterstitial = adAuto.getAttribute("data-vignette-loaded") === "true";  // 插屏
		isInPageAd = adAuto.getAttribute("data-ad-format") === "auto"  // 页内
		isDisplayAd = !!adAuto.getAttribute("data-ad-slot");  // 手动
		isAnchorAd = adAuto.getAttribute("data-anchor-ad") === "true";  // 手动锚点anchor
		isAutoAnchorAd = adAuto.getAttribute("data-anchor-shown") === "true";  // 自动锚点anchor
		if (isAFC) {
			// 自动插屏广告上报
			if (isInterstitial) {
				logEvent('AD_Inter_Click');
			}
	
			// 自动页内广告上报
			if (isInPageAd) {
				logEvent('AD_InP_Click', {
					Page: page
				});
			}
	
			// 自动锚点anchor上报
			if (isAutoAnchorAd) {
				logEvent('AD_Anc_Click', {
					Page: page
				});
			}
	
			// 自动插屏广告+自动页内广告上报 + 手动广告（不含底部锚点）
			if (isInterstitial || isInPageAd || (isDisplayAd && !isAnchorAd)) {
				logEvent('AD_IntInClick');
			}
		}
		if (isGAM) {
			logEvent('GAM_AD_Click_Auto');
			// 自动插屏广告上报
			if (isInterstitial) {
				logEvent('GAM_Inter_Click_Auto');
			}
			// 锚点广告上报
			if (isAutoAnchorAd) {
				logEvent('GAM_Anc_Click_Auto');
			}
		}
	}

	// AFC手动广告点击
	let adContainer = ACTIVELEMENT.closest("[data-ad-slot]");
	if (adContainer) {
		logEvent('AD_Click', {
			Page: page
		})
	}
	// GAM手动/自动广告点击
	let adGam = ACTIVELEMENT.id.includes('gpt')
	if (adGam) {
		logEvent('GAM_AD_Click_All');
	}

	// 手动锚点广告
	let anchorAd = ACTIVELEMENT.closest("[anchor-ad]");
	// GAM手动广告
	let gamHandle = ACTIVELEMENT.id.includes('div-gpt-ad-');
	// GAM的自动插屏广告/GAM手动广告/AFC手动广告（排除anchor-ad的广告）
	let GAM_IntIn_Click = ((isGAM && isInterstitial) || gamHandle || adContainer) && !anchorAd;
	if (GAM_IntIn_Click) {
		logEvent('GAM_IntIn_Click');
	}

	// 广告点击次数
	if (process.client && (adGam || adContainer)) {
		const clickAdCount = Number(sessionStorage.getItem('_trackCount')) + 1
		sessionStorage.setItem('_trackCount', clickAdCount.toString())
	}
};
// 页面失去焦点
const windowBlur = () => {
	window.addEventListener("blur", () => {
		let ACTIVELEMENT = document.activeElement;
		if (!!ACTIVELEMENT && ACTIVELEMENT?.nodeName === "IFRAME") {
			isBlurTriggered.value = true;
			setTimeout(() => {
				isBlurTriggered.value = false;
			}, 300);
			setTimeout(() => {
				window.focus();
				if (ACTIVELEMENT && ACTIVELEMENT instanceof HTMLElement) {
					ACTIVELEMENT.focus();
				}
			}, 0);
		}
	});
};

// 页面展示隐藏
const windowVisible = () => {
	window.addEventListener("visibilitychange", () => {
		if (document.visibilityState == "hidden" && isBlurTriggered.value)
			trackAdClick();
	});
};

// 关闭页面之前
const windowBeforeUnload = () => {
	window.addEventListener("beforeunload", () => {
		let ACTIVELEMENT = document.activeElement;
		if (!!ACTIVELEMENT && ACTIVELEMENT?.nodeName === "IFRAME") {
			if (window.location.hash.indexOf('vignette') > -1) {
				// 页面内跳转，非广告点击 **待完善**
			} else {
				trackAdClick();
			}
		};
	});
};

// 监听 AdSense 自动广告的显示并上报埋点
const listenAutoAds = () => {
	// 已经上报的广告元素集合，防止重复上报
	const reportedAds = new Set();
  
	// 初始化处理 AdSense自动 广告
	const afcElements = document.querySelectorAll('.adsbygoogle-noablate');
	afcElements.forEach((ad) => processAdNode(ad, 'afc'));

	// 初始化处理 GAM自动 广告
	const gamElements = document.querySelectorAll('[data-google-query-id]');
	gamElements.forEach((ad) => {
		if (ad.tagName.toLowerCase() !== 'ins') return;
		processAdNode(ad, 'gam');
	});
  
	// 动态新增广告检测：通过 MutationObserver 监听广告节点新增
	const observer = new MutationObserver((mutationsList) => {
	  mutationsList.forEach((mutation) => {
		mutation.addedNodes.forEach((node) => {
		  if (isAdAutoNode(node, 'afc')) {
			processAdNode(node, 'afc');
		  } else if (isAdAutoNode(node, 'gam')) {
            processAdNode(node, 'gam');
          }
		});
	  });
	});
  
	// 开始监听全局 DOM 树的变化（扩展到整个子树，捕获动态加载的广告位）
	observer.observe(document.body, {
	  childList: true,
	  subtree: true,
      attributes: true,
      attributeFilter: ['data-google-query-id', 'data-ad-status']
	});

	// 新建一个函数，用来判断是什么类型的广告
	function getAdType(ad: any) {
        if (!ad || typeof ad.getAttribute !== "function") {
            return {
                show: 'Auto_Unknown_AD_Show',
                fail: 'Auto_Unknown_AD_Show_Fail'
            };
        }
    
        const hasNoablate = ad.querySelectorAll('.adsbygoogle-noablate').length > 0;
        const id = ad.id || '';
        const vignetteLoaded = ad.getAttribute('data-vignette-loaded') === 'true';
        const adFormatAuto = ad.getAttribute('data-ad-format') === 'auto';
        const anchorShown = ad.getAttribute('data-anchor-shown') === 'true';
    
        let adType = 'unknown';
        if (hasNoablate) {
            if (vignetteLoaded) return AD_EVENTS['inter'];
            if (adFormatAuto)   return AD_EVENTS['inp'];
            if (anchorShown)    return AD_EVENTS['anchor'];
        } else if (id.includes('gpt')) {
            if (vignetteLoaded) return AD_EVENTS['gam_inter'];
            if (anchorShown)    return AD_EVENTS['gam_anchor'];
        }
    
        return AD_EVENTS['unknown'];
    }
    
    // 放在函数外部，避免多次分配
    const AD_EVENTS = {
        'inter': {
            show: 'Auto_Inter_AD_Show',
            fail: 'Auto_Inter_AD_Show_Fail'
        },
        'inp': {
            show: 'Auto_InP_AD_Show',
            fail: 'Auto_InP_AD_Show_Fail'
        },
        'anchor': {
            show: 'Auto_Anc_AD_Show',
            fail: 'Auto_Anc_AD_Show_Fail'
        },
        'gam_inter': {
            show: 'GAM_Inter_AD_Show_Auto',
            fail: 'GAM_Inter_AD_Show_Fail_Auto'
        },
        'gam_anchor': {
            show: 'GAM_Anc_AD_Show_Auto',
            fail: 'GAM_Anc_AD_Show_Fail_Auto'
        },
        'unknown': {
            show: 'Auto_Unknown_AD_Show',
            fail: 'Auto_Unknown_AD_Show_Fail'
        }
    };
  
	/**
	 * 通用函数：处理广告节点，监听加载状态，报告广告展示埋点
	 */
	function processAdNode(ad: any, type: string) {
		if (reportedAds.has(ad)) return; // 广告已处理，跳过
				
		// 监听广告状态
		const attrObserver = new MutationObserver(() => {
            if (type === 'afc') {
                const adStatus = ad.getAttribute('data-ad-status');
                const computedStyle = window.getComputedStyle(ad).display;
                const autoAdType = getAdType(ad);
                
                if (adStatus === 'filled' && computedStyle === 'block') {
                    logEvent('Auto_AD_Show');
                    logEvent(autoAdType.show);
                    reportedAds.add(ad);
                    attrObserver.disconnect();
                } else {
                    logEvent('Auto_AD_Show_Fail');
                    logEvent(autoAdType.fail);
                }
            } else if (type === 'gam') {
                const hasQueryId = ad.hasAttribute('data-google-query-id');
                const computedStyle = window.getComputedStyle(ad).display;
				const displayAd = ad.hasAttribute('data-anchor-status') === 'displayed';
                const autoAdType = getAdType(ad);

                if (hasQueryId && computedStyle !== 'none' && displayAd) {
                    logEvent('GAM_AD_Show_Auto');
                    logEvent(autoAdType.show);
                    reportedAds.add(ad);
                    attrObserver.disconnect();
                } else {
                    logEvent('GAM_AD_Show_Fail_Auto');
                    logEvent(autoAdType.fail);
                }
            }
		});

		// 监听广告状态变化
		attrObserver.observe(ad, {
			attributes: true,
			attributeFilter: type === 'afc' ? ['data-ad-status'] : ['data-google-query-id']
		});

		// 设置超时检测
		setTimeout(() => {
			if (!reportedAds.has(ad)) {
				const autoAdType = getAdType(ad);
				const adTagType = ad.tagName.toLowerCase();
				console.log(`广告加载超时: ${type} - ${adTagType}`);
				if (type === 'afc') {
					logEvent('Auto_AD_Show_Fail');
				} else {
					adTagType === 'ins' && logEvent('GAM_AD_Show_Fail_Auto');
				}
				logEvent(autoAdType.fail);
				attrObserver.disconnect();
			}
		}, 10000);
	}

	// 判断是否为自动广告节点
	const isAdAutoNode = (node: any, type: string) => {
	  if (type === 'afc') {
          return node.nodeType === 1 && node.classList.contains('adsbygoogle-noablate');
      } else if (type === 'gam') {
          return node.nodeType === 1 && 
		  		node.id.includes('gpt') && 
                 (node.tagName.toLowerCase() === 'ins' || node.tagName.toLowerCase() === 'div');
      }
      return false;
	}
}

const getUrlParams = () => {
    const NuxtUrl = useRequestURL();
    return {
        channel: NuxtUrl.searchParams.get("channel") || "",
        network: NuxtUrl.searchParams.get("network") || "",
        pid: NuxtUrl.searchParams.get("pid") || ""
    };
};
export const initServer = ()=>{
	console.log("初始化广告---------");
	
	return new Promise((resolve)=>{
		// 初始化js引入
		const { channel, network, pid } = getUrlParams();
		const javascriptArr = [...initGtag(), ...initPosthog(), ...initAdsense(channel), ...initGAM(), ...initPixel(network, pid)];
		useHead({ script: javascriptArr });
		resolve(true)
	})
}

export const initClient = () => {
	console.log("开始监听广告点击---------");
	if (!import.meta.server) {
		const { channel } = getUrlParams();
		windowBlur();
		windowVisible();
		windowBeforeUnload();
		initGAMSlots(channel);
		listenAutoAds()
	}
};